<?
//error_reporting(E_ALL);
//Initiate Authenticate
SecurityRedirect ();
//error_reporting(E_ALL);
//initiate Vars 
define("PRIMARY_KEY","nokwit");
$PRIMARY_KEY    = PRIMARY_KEY;
$PRIMARY_VALUE  = GetParam($PRIMARY_KEY,"");
$FileName       = "ais_transaction_receipt_entry.php";
$FileTemplate   = "ais_transaction_receipt_entry_form.html";
$SubHeaderTitle = "Transaction Receipt - Entry Receipt";
$TableName		  = "ais_receipt";
$HTMLFormName   = "ReceiptForm";
$MaxGrid        = "100";
$KTRASL		= GetOfficeID();
//$HTMLFormName2  = "BudgetForm";

$FormAction    = $FileName . "?" . AddParam(GetQueryString("QueryString", ""),"form","$HTMLFormName");
$FormEncType   = "application/x-www-form-urlencoded";
//$PMode         = "";

//Initiate Grid Fields;
$FormFields    = array("receipt_id"=>"","urut"=>"0","thbl"=>"","uraian"=>"0","uraian_tools"=>"0","jumlah"=>"number","skada"=>"0","vessel"=>"","voyage"=>"","cbm"=>"","jenis"=>"","dol"=>"","inc_ppn"=>"","kdact"=>"","container_no"=>"","jenis"=>"number","dol"=>"number");

//buildsqlfield ("$TableName", $FormFields);

//Leave Here Untouch
$FormCName     = BuildHTMLField($FormFields,"name",1);
$FormCValue    = BuildHTMLField($FormFields,"value",1);

//************ FORM ACTION **************
if (trim(GetParam("form",""))==trim($HTMLFormName)) {
	if (GetParam("FormAction","")=="Save") {
		list($FDay,$FMonth,$FYear) = explode("/",GetParam("tglkwit",""));
		$tglkwit = "$FYear-$FMonth-$FDay";
        if (GetParam("duedate","")) {
            list($FDay,$FMonth,$FYear) = explode("/",GetParam("duedate",""));
            $duedate = "$FYear-$FMonth-$FDay";
        }
		$rate    = StrToNumber (GetParam("rate",""));

		if (trim(GetParam("nokwit",""))=="AUTO NUMBERED BY SYSTEM")	{
			$ObjNumber  = new autonumber(GetParam("tglkwit",""));
			$TransNo = $ObjNumber->GetNumber("KW");
			FormSave($TableName, "uraian", $FormFields, array("ledger"=>GetPeriod(GetParam("tglkwit","")),"debnam"=>GetParam("debnam",""),"nokwit"=>$TransNo,"npwp"=>GetParam("npwp",""),"tglkwit"=>"$tglkwit","remark1"=>GetParam("remark1",""),"remark2"=>GetParam("remark2",""),"remark3"=>GetParam("remark3",""),"payby"=>GetParam("payby",""),"duedate"=>$duedate,"nocek"=>GetParam("nocek",""),"curr"=>GetParam("curr",""),"rate"=>$rate,"debtur"=>GetParam("debtur",""),"ktrasl"=>GetOfficeID(),"app1"=>GetParam("app1",""),"nmapp1"=>GetParam("nmapp1",""),"principal"=>GetParam("principal",""),"principal_code"=>GetParam("principal_code",""),"alamat"=>GetParam("alamat",""),"faktur"=>GetParam("faktur",""),"noppn"=>GetParam("IncPPN",""),"location"=>GetParam("location","")),"receipt_id");
			SetLogActivity($TransNo,"Create","");

    } else {

			$TransNo = GetParam("nokwit","");
			//Delete row with skada PPN
			$SQL = "DELETE FROM $TableName WHERE skada like '".GetPPNSkada()."' AND nokwit = '$TransNo' ";
			$DBConnection->dbc->query($SQL);
			FormSave($TableName, "uraian", $FormFields, array("ledger"=>GetPeriod(GetParam("tglkwit","")),"debnam"=>GetParam("debnam",""),"nokwit"=>$TransNo,"npwp"=>GetParam("npwp",""),"tglkwit"=>"$tglkwit","remark1"=>GetParam("remark1",""),"remark2"=>GetParam("remark2",""),"remark3"=>GetParam("remark3",""),"payby"=>GetParam("payby",""),"duedate"=>$duedate,"nocek"=>GetParam("nocek",""),"curr"=>GetParam("curr",""),"rate"=>$rate,"debtur"=>GetParam("debtur",""),"ktrasl"=>GetOfficeID(),"app1"=>GetParam("app1",""),"nmapp1"=>GetParam("nmapp1",""),"principal"=>GetParam("principal",""),"principal_code"=>GetParam("principal_code",""),"alamat"=>GetParam("alamat",""),"faktur"=>GetParam("faktur",""),"noppn"=>GetParam("IncPPN",""),"location"=>GetParam("location","")),"receipt_id");
			SetLogActivity($TransNo,"Update","");
		}
			$SQL = "
				SELECT SUM(ais_receipt.jumlah)
				FROM ais_receipt
				INNER JOIN tblcoa ON ais_receipt.skada = tblcoa.skada AND tblcoa.inc_ppn=1 AND tblcoa.ledger='".GetLedgerFromCOA()."'
				WHERE nokwit='$TransNo'
				";
			$Jumlah = $DBConnection->dbc->get_var($SQL);
			
			if ($Jumlah>0) {

			$DBConnection->AddData("urut","998");
			$DBConnection->AddData("uraian","PPN 10%");
			$DBConnection->AddData("uraian_tools","PPN 10%");
			//$DBConnection->AddData("jumlah",StrToNumber(GetParam("total_ppn","")));
			$DBConnection->AddData("skada",GetPPNSkada());
			$DBConnection->AddData("curr",GetParam("curr",""));
			$DBConnection->AddData("rate",StrToNumber(GetParam("rate","")));
			$DBConnection->AddData("jenis",1);
			$DBConnection->AddData("dol",StrToNumber(GetParam("total_ppn","")));
			$DBConnection->AddData("location",GetParam("location",""));
			$DBConnection->AddData("jumlah",StrToNumber(GetParam("total_ppn","")));
			$DBConnection->AddData("rupiah",StrToNumber(GetParam("total_ppn",""))*StrToNumber(GetParam("rate","")));
			$DBConnection->AddData("ledger",GetPeriod(GetParam("tglkwit","")));
			$DBConnection->AddData("debnam",GetParam("debnam",""));
			$DBConnection->AddData("debtur",GetParam("debtur",""));
			$DBConnection->AddData("noppn",GetParam("IncPPN",""));
			$DBConnection->AddData("remark1",GetParam("remark1",""));
			$DBConnection->AddData("nokwit",$TransNo);
			$DBConnection->AddData("faktur",GetParam("faktur",""));
			$DBConnection->AddData("npwp",GetParam("npwp",""));
			$DBConnection->AddData("tglkwit",$tglkwit);
			$DBConnection->AddData("ktrasl",GetOfficeID());
			$SQL = "SELECT untush FROM tblcoa WHERE skada='".GetPPNSkada()."'";
			$Untush = $DBConnection->dbc->get_var($SQL);

			$DBConnection->AddData("kdact",$Untush);
			$DBConnection->AddData("principal",GetParam("principal",""));
			$DBConnection->AddData("principal_code",GetParam("principal_code",""));
			$DBConnection->AddData("alamat",GetParam("alamat",""));
			$DBConnection->InsertData($TableName);

			}
			
			if (trim(GetParam("nokwit",""))=="AUTO NUMBERED BY SYSTEM") CreateNPWP($TransNo);
			//Insert row with skada PPN
			
	    if (GetParam("CreateTK","")==1) {
        CreateTK($TransNo);
      }

		DeleteRecord ("txtCheck",$MaxGrid);
		header("Location: $FileName?PageMode=Form&nokwit=$TransNo");
		exit;
	}

	if (GetParam("FormAction","")=="Delete") {
//		print "Deleted"."<br>\n";
		FormDelete();
		//SetLogActivity($TransNo,"Delete","");
		//DeleteRecord ("txtCheck",$MaxGrid);
	}

} else if ((GetParam("Action","")=="CreateFaktur") && GetParam($PRIMARY_KEY,"")) {
	CreateNPWP(GetParam(PRIMARY_KEY,""));
}

//Field Verification 
$Verification  = "False";
$SessionVar    = md5(microtime());
//$SessionVar    = "Stuck";
$VerifyFields = array("nokwit"=>"ID No.","tglkwit"=>"Transaction Date","principal_code"=>"Opr. Contr","location"=>"Location",
		      "skada1"=>"Skada On Line 1",
		      "curr"=>"Currency",
		      "payby"=>"Payment By");

VerifyHTML ($HTMLFormName,$VerifyFields,$SessionVar,array("debtur"=>"Received From"));

if (GetParam(PRIMARY_KEY,"")) {
	$SQLCount     = "SELECT count(*) FROM `$TableName`";
	$SQLCount    .= "WHERE ".PRIMARY_KEY."='".$PRIMARY_VALUE."' AND skada not like '".GetPPNSkada()."'";
	$Count        = $DBConnection->dbc->get_var($SQLCount);
} else $Count=0;

$NewDataStart = $Count+1;
$InitFunction = "Masking();Masking2();";
$VerifyGrids = array("uraian"=>"0","uraian_tools"=>"0","jumlah"=>"number","skada"=>"0");
$Masking1 = BuildMasking ($HTMLFormName,MutatorFields($FormFields,($MaxGrid+$Count)));
$Masking2 = BuildMasking ($HTMLFormName,array("tglkwit"=>"date","rate"=>"number","duedate"=>"date"),"2");
$JSMasks  = $Masking1.$Masking2;

Init($SessionVar,$JSMasks);
FormGridHTML ($HTMLFormName,$VerifyGrids,$Count,$MaxGrid,$SessionVar);

//************ SET FORM MODE ***************
if (GetParam(PRIMARY_KEY,"")) {  
  $FormMode = "Edit";
  /*
  if (!isApproved(GetParam("nokwit",""))) $USER_CANPRINT="";
  else $USER_CANPRINT="1";
  */
  $USER_CANPRINT="1";
} else {
  $FormMode = "Add";
  $USER_CANPRINT="";
}


//******* DATABASE GRID QUERY ***********
$SQL = "SELECT ".BuildFields($FormFields)." FROM `$TableName`";
if (GetParam(PRIMARY_KEY,"") && $FormMode="Edit") {
    $SQLGrid  = $SQL."WHERE ".PRIMARY_KEY." ='".GetParam(PRIMARY_KEY,"")."' AND skada not like '".GetPPNSkada()."'";
    $SQLGrid .= " ORDER BY ".PRIMARY_KEY;
} 


//******* SHOW FORM CONTENT *********
$TBS = new clsTinyButStrong ;
$TBS->LoadTemplate($MOD_TEMPLATE_DIR."/".$FileTemplate);

//********************************* HTML Header ******************************************

//Select Currency Table
$SQLCurr = "SELECT * FROM tblcurrency";
//Select Department:
$SQLDept = "SELECT * FROM tbldept";
//Select Receipt:
$SQLReceipt = "SELECT * FROM tblreceipt";
//Select Activity
$SQLAct  = "SELECT  * FROM tblactivity ORDER BY kdact";

$HeaderFields = array("debnam"=>"0","nokwit"=>"0","npwp"=>"","tglkwit"=>"date","alamat"=>"","faktur"=>"","remark1"=>"","remark2"=>"","remark3"=>"","payby"=>"","duedate"=>"","nocek"=>"","curr"=>"","rate"=>"number","debtur"=>"","app1"=>"","nmapp1"=>"","principal"=>"","principal_code"=>"","alamat"=>"","noppn"=>"","location"=>"");

//Leave Here Untouch
$FormCName     = BuildHTMLField($HeaderFields,"name",1);
$FormCValue    = BuildHTMLField($HeaderFields,"value",1);
$SQLHeader     = "SELECT ".BuildFields($HeaderFields)." FROM $TableName ";
$SQLLocation   = "SELECT * FROM $DBCoins.tblsubdepo";

if (GetParam(PRIMARY_KEY,"") && $FormMode="Edit") $SQLHeader .= "WHERE ".PRIMARY_KEY."='".GetParam(PRIMARY_KEY,"")."' AND ktrasl='".GetOfficeID()."'";
$TBS->MergeBlock("currformblk",$DBMysql,$SQLCurr);
$TBS->MergeBlock("locblk",$DBMysql,$SQLLocation);
$TBS->MergeBlock("actblk",$DBMysql,$SQLAct);
$TBS->MergeBlock("receiptblk",$DBMysql,$SQLReceipt);

// HTML Value
$TBS->MergeBlock("headbln",$FormCName);
if (GetParam(PRIMARY_KEY,"")) {$TBS->MergeBlock("headblv",$DBMysql,$SQLHeader);}
else $TBS->MergeBlock("headblv",$FormCValue);

//********************************* HTML GRID *********************************************
//HTML Grid
//print $SQLGrid;
if (strlen($SQLGrid)) $Result = $DBConnection->dbc->get_results($SQLGrid,ARRAY_A);
$Result  = BuildEmptyGrid ($FormFields, $MaxGrid, $Result);

$TBS->MergeBlock("blg",$Result);
$TBS->Show();

//*************** ACTION FUNCTION *******************
function isApproved($nokwit) {
	global $DBConnection,$TableName;
        $SQL = "SELECT app1 FROM $TableName WHERE nokwit='$nokwit' limit 1";
        return $DBConnection->dbc->get_var($SQL);
}

function FormInsert() {
	global $DBConnection,$FileName;
	$DBConnection->Insert();
	header("Location: $FileName?PageMode=Form");
	exit;
}

function FormUpdate() {
	global $DBConnection;
	$DBConnection->Update();
}

function FormDelete() {
	global $DBConnection,$FileName,$TableName;
	$DBConnection->deleteGrid("$TableName",PRIMARY_KEY,PRIMARY_KEY);
	header("Location: $FileName");
	exit;	
}

function FormSearch () {

}

function FormCancel () {
	global $FileName;
	header("Location: ".$FileName);
	exit;
}

function FormSave ($table, $keyField, $FormFields, $SpecialCase="", $PrimaryKey) {
	global $FileName, $MaxGrid, $DBConnection;
	$TotalData = $MaxGrid * 2;	
	$NewDataStart = GetParam("NewData","0");
	for ($a=1;$a<=$TotalData;$a++) {
		foreach ($FormFields as $key=>$formatting) {
			if (!GetParam($keyField.$a,"")) {
				$EndOfData = 1;
				break;
			}
			$value = GetParam($key.$a,"");
			if ($formatting=="number") $value = str_replace(",","",$value);
			if ($formatting=="date") {
				list($day,$month,$year) = explode("/",$value);
				$value = "$year-$month-$day";
		    }
			$DBConnection->add_data($table,$key,addslashes($value));
		}
		$rate = StrToNumber(GetParam("rate",""));
		$jmh  = StrToNumber(GetParam("jumlah".$a,""));
		$rupiah = $rate * $jmh;
		$DBConnection->add_data($table,"rupiah",$rupiah);
		if ($EndOfData) {
			break;
	    }
		if (strlen($SpecialCase)) {
			foreach ($SpecialCase as $key => $value) {
			//	print "add_data($table,$key,$value);<br>";
				$DBConnection->add_data($table,$key,addslashes($value));
			}
		}
//		print "$a < $NewDataStart<br>";
		if ($a < $NewDataStart) {
			 if (strlen($PrimaryKey)) {
			    $DBConnection->UpdateGrid($PrimaryKey,GetParam($PrimaryKey.$a,""));
		 	 } else {
			    $DBConnection->UpdateGrid($keyField,addslashes(GetParam($keyField.$a,"")));
		     }
		} else {
			$DBConnection->InsertGrid();
//                        $DBConnection->dbc->debug();
	    }
	}
}
//*************** USER FUNCTION *******************
function buildsqlfield ($table, $arrayfield) {
		global $DBConnection;
		for ($x=0;$x<count($arrayfield);$x++) {
			$DBConnection->add_htmlfield($table,$arrayfield[$x],GetParam($arrayfield[$x],""));
		}
}

function DeleteRecord ($sequence_name,$PageSize) {
	global $DBConnection,$FileName,$TableName;	
	for ($x=1;$x<=$PageSize;$x++) {				
		if (GetParam($sequence_name.$x,""))	{
			$DBConnection->deleteGrid("$TableName","receipt_id",$sequence_name.$x);
	    }
	}
}

function BuildFields ($FormFields) {
		global $DBConnection;
		$str = "";
		foreach ($FormFields as $key=>$formatting) {
			if (strlen($str)) $str .= ",$key";
			else $str = "$key";
		}
		return $str;
}

function MutatorFields ($FormFields, $MaxGrid) {
		global $DBConnection;
		$array_fields = array();
		for ($x=0;$x<$MaxGrid;$x++) {
			foreach ($FormFields as $key=>$formatting){
				$a=$x+1;
				$array_fields[$key.$a] = "$formatting";
			}			
		}
		return $array_fields;
}

function CreateNPWP($nokwit) {
	global $DBConnection,$DBGeneral,$DBName,$DBProcess;
	$SQL = "SELECT skada,tglkwit,ktrasl FROM ais_receipt WHERE nokwit='$nokwit' AND skada='".GetPPNSkada()."' ";
	$row = $DBConnection->dbc->get_row($SQL);
	$ktrasl = $row->ktrasl;
	//print_r($row);
	if (!strlen($row->skada)) return;
	$FDate = explode("-",$row->tglkwit); 
	$Year  = substr($FDate[0], -2);

	$SQL = "SELECT npwp FROM ais_receipt WHERE nokwit='$nokwit' ";
	$isNPWP = $DBConnection->dbc->get_var($SQL);

	$SQL = "SELECT taxcode,taxprefix FROM tblprofile ";
	$TaxResult = $DBConnection->dbc->get_row($SQL);

	if (strlen($isNPWP)) {
/*	
	  if (intval($Year)<7)
	  $NumberStr = "DL";
	  else
*/
	// STANDARD
	$NumberStr = $TaxResult->taxprefix.".".$TaxResult->taxcode."-".$Year.".";		
	$SQL = "SELECT vat FROM $DBProcess.view_faktur_no WHERE substr(vat,9,2)='$Year' and vat not like '$ktrasl%' ORDER BY right(vat,8) DESC LIMIT 1";
	$LastTransNo = $DBConnection->dbc->get_var($SQL);
	} else {
	// SEDERHANA
	$NumberStr = $TaxResult->taxcode."-";
	$SQL = "SELECT vat FROM $DBProcess.view_faktur_no WHERE  vat like '$ktrasl%' ORDER BY right(vat,8) DESC LIMIT 1";
	$LastTransNo = $DBConnection->dbc->get_var($SQL);
	}
//  $LengthNumber = strlen($NumberStr)+8;
/*
  if (intval($Year)>=7)
	 $SQL = "SELECT vat FROM $DBProcess.view_faktur_no WHERE vat like '$NumberStr%' AND tglbkt>='2007-01-01' AND length(vat)=$LengthNumber ORDER BY vat DESC LIMIT 1";
	else 
   $SQL = "SELECT vat FROM $DBProcess.view_faktur_no WHERE vat like '$NumberStr%' AND tglbkt<'2007-01-01'  AND length(vat)=$LengthNumber ORDER BY vat DESC LIMIT 1";
*/
  
  if ($isNPWP) {
      //die("shit"." ".$LastTransNo."<p> ".$SQL);
      /*  
    if (ereg("DL",$LastTransNo)) {
        $Urut = substr($LastTransNo, -5);
    	  $Urut = intval($Urut)+1;    
        $SQL = "SELECT LPAD('$Urut',5,'0')";
        $NumberStr = substr($LastTransNo, 0, 10);
    } else {
    */
        $Urut = substr($LastTransNo, -8);
    	$Urut = intval($Urut)+1;
        $SQL = "SELECT LPAD('$Urut',8,'0')";
//    }
  } else {
//    if (intval($Year)>=7) {
      $Urut = substr($LastTransNo, -8);
      $Urut = intval($Urut)+1;
      $SQL = "SELECT LPAD('$Urut',8,'0')";
/*      
    } else {
      $Urut = substr($LastTransNo, -5);
      $Urut = intval($Urut)+1;
      $SQL = "SELECT LPAD('$Urut',5,'0')";
      $NumberStr = substr($LastTransNo, 0, 4);
    }
*/     
  }

	$Urut = $DBConnection->dbc->get_var($SQL);
	$NumberStr = $NumberStr.$Urut; 

	$SQL = "UPDATE ais_receipt SET faktur='$NumberStr' WHERE nokwit='$nokwit' ";
	$DBConnection->dbc->query($SQL);
}



function CreateTK($nokwit) {
  global $DBConnection;
  $tglkwit = GetParam("tglkwit","");
  list($FDay,$FMonth,$FYear) = explode("/",$tglkwit);
  $SQL = "
    SELECT kdcash,coa,tblcoa.untush,tglkwit 
    FROM ais_receipt 
    INNER JOIN tblcash ON ais_receipt.curr=tblcash.symbol
    INNER JOIN tblcoa ON tblcoa.skada=tblcash.coa AND tblcoa.ledger='".GetLedgerFromCOA()."'
    WHERE nokwit = '$nokwit'
  ";

  $Row = $DBConnection->dbc->get_row($SQL);
//  list($FYear,$FMonth,$FDay) = explode("-",$Row->tglkwit);
//	$tglkwit = "$FDay/$FMonth/$FYear";

  $ObjNumber  = new autonumber($tglkwit,$Row->kdcash);
	$TransNo = $ObjNumber->GetNumber('ZTK');

  $SQL = "INSERT INTO ais_memorial_z 
                 (source,urut,ktrasl,kdcash,payby,ledger,curr,rate,nobkt,tglbkt,dk,noorder,debtur,debnam,skada,kdact,uraian,jumlah,rupiah,noref,location) 
          SELECT 'Other',urut,ktrasl,'{$Row->kdcash}','Transfer',ledger,curr,rate,'$TransNo',tglkwit,'K',noorder,debtur,debnam,skada,kdact,uraian,jumlah,rupiah,'$nokwit',location FROM ais_receipt WHERE nokwit='$nokwit' ";
  $DBConnection->dbc->query($SQL);
//  $DBConnection->dbc->debug();
//  $SQL = "INSERT INTO ais_memorial (source,urut,ktrasl,kdcash,payby,ledger,curr,rate,nobkt,tglbkt,dk,noorder,debtur,debnam,skada,kdact,uraian,jumlah,rupiah,noref) VALUES ('','999','".GetOfficeID()."','$kdcash','Transfer','".GetPeriod(GetParam("tglkwit",""))."',curr,rate,nobkt,tglbkt,dk,noorder,debtur,debnam,skada,kdact,uraian,jumlah,rupiah,noref)";
//  $DBConnection->dbc->query($SQL);
			$DBConnection->AddData("source","Other");
			$DBConnection->AddData("urut","999");
			$DBConnection->AddData("kdcash",$Row->kdcash);
			$DBConnection->AddData("payby",'Transfer');
			$DBConnection->AddData("ledger",GetPeriod(GetParam("tglkwit","")));
			$DBConnection->AddData("curr",GetParam("curr",""));
			$DBConnection->AddData("rate",StrToNumber(GetParam("rate","")));
			$DBConnection->AddData("location",GetParam("location",""));
			$DBConnection->AddData("tglbkt",GetParam("tglkwit",""));
			$DBConnection->AddData("nobkt",$TransNo);
			$DBConnection->AddData("noref",$nokwit);
			$DBConnection->AddData("uraian",$nokwit);
      $DBConnection->AddData("app1",GetUserID());
      $DBConnection->AddData("app2",GetUserID());
      $DBConnection->AddData("nmapp1",GetStaffName());
      $DBConnection->AddData("nmapp2",GetStaffName());			
			$DBConnection->AddData("dk",'D');
			$DBConnection->AddData("skada",$Row->coa); // belum
			$DBConnection->AddData("jumlah",StrToNumber(GetParam("total_trans","")));
			$DBConnection->AddData("rupiah",StrToNumber(GetParam("total_trans",""))*StrToNumber(GetParam("rate","")));
			$DBConnection->AddData("debnam",GetParam("debnam",""));
			$DBConnection->AddData("debtur",GetParam("debtur",""));
			$DBConnection->AddData("tglbkt",$Row->tglkwit);
			$DBConnection->AddData("ktrasl",GetOfficeID());
			$DBConnection->AddData("kdact",$Row->untush); //belum
			$DBConnection->InsertData('ais_memorial_z');
//			$DBConnection->dbc->debug();
}
?>
